package com.zqxx.examine.portal.service;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zqxx.examine.common.utils.Page;
import com.zqxx.examine.model.user.Department;
import com.zqxx.examine.model.user.Group;
import com.zqxx.examine.model.user.Role;
import com.zqxx.examine.model.user.User;
import com.zqxx.examine.portal.persistence.UserMapper;

@Service
public class  UserService
{
  @Autowired
  public UserMapper userMapper;
  
  @Transactional
  public int addUser(User user, String authority, int groupId, HashMap<String, Role> roleMap)
  {
    try
    {
      int userId = -1;
      this.userMapper.insertUser(user);
      userId = user.getUserId();
      this.userMapper.grantUserRole(userId, ((Role)roleMap.get(authority)).getRoleId());
      if (user.getDepId() != 0) {
        this.userMapper.addUser2Dep(userId, user.getDepId());
      }
      return userId;
    }
    catch (Exception e)
    {
      String cause = e.getCause().getMessage();
      throw new RuntimeException(cause);
    }
  }
  
  @Transactional
  public void updateUser(User user, String oldPassword)
  {
    try
    {
      this.userMapper.updateUser(user, oldPassword);
      this.userMapper.deleteUser2Dep(user.getUserId());
      this.userMapper.addUser2Dep(user.getUserId(), user.getDepId());
    }
    catch (Exception e)
    {
      String cause = e.getCause().getMessage();
      throw new RuntimeException(cause);
    }
  }
  
  public List<Group> getGroupListByUserId(int userId, Page<Group> page)
  {
    return this.userMapper.getGroupListByUserId(userId, page);
  }
  
  public HashMap<String, Role> getRoleMap()
  {
    List<Role> roleList = this.userMapper.getRoleList();
    HashMap<String, Role> map = new HashMap();
    for (Role r : roleList) {
      map.put(r.getAuthority(), r);
    }
    return map;
  }
  
  public void changeUserStatus(List<Integer> idList, boolean enabled)
  {
    this.userMapper.changeUserStatus(idList, enabled);
  }
  
  public void addUserGroup(int userId, int groupId)
  {
    this.userMapper.addUserGroup(userId, groupId);
  }
  
  public void deleteUserGroup(int userId, int groupId, int managerId)
  {
    this.userMapper.deleteUserGroup(userId, groupId, managerId);
  }
  
  public List<Department> getDepList(Page<Department> page)
  {
    return this.userMapper.getDepList(page);
  }
  
  public User getUserByName(String userName)
  {
    return this.userMapper.getUserByName(userName);
  }
  
  public void updateUserPwd(User user, String oldPwd)
  {
    this.userMapper.updateUser(user, oldPwd);
  }
}
